package com.jyw.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jyw.R;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.Address;
import com.jyw.pojo.EventBusTypes;
import com.jyw.pojo.ShangPin;
import com.jyw.utils.DimenUtils;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/11
 */

public class MallActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView recycler;
    private SPAdapter adapter;
    private String sp_id, sp_integral;
    private RelativeLayout layoutHistory, layoutJifen;
    private LinearLayout layoutChoujiang;
    private TextView tvIntegralGet;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_mall);

        recycler = (RecyclerView) findViewById(R.id.recycler);
        layoutHistory = (RelativeLayout) findViewById(R.id.layout_history);
        layoutJifen = (RelativeLayout) findViewById(R.id.layout_jifen);
        tvIntegralGet = (TextView) findViewById(R.id.tv_integral_get);
        layoutChoujiang = (LinearLayout) findViewById(R.id.layout_choujiang);

        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        layoutHistory.setOnClickListener(this);
        layoutJifen.setOnClickListener(this);
        tvIntegralGet.setOnClickListener(this);
        layoutChoujiang.setOnClickListener(this);

        recycler.setLayoutManager(new GridLayoutManager(MallActivity.this, 3));
        recycler.addItemDecoration(new SpacesItemDecoration(DimenUtils.dip2px(MallActivity.this, 4f),
                DimenUtils.dip2px(MallActivity.this, 4f)));
        recycler.setAdapter(adapter = new SPAdapter());

        loadMallData();
    }

    private void loadMallData() {
        Request request = new Request.Builder().url(Server.GET_INTEGRAL_MALL).build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(MallActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JSONArray arr;
                final List<ShangPin> sPs = new ArrayList<>();
                try {
                    arr = new JSONArray(response.body().string());
                    if (arr.length() > 0) {
                        Gson gson = new Gson();
                        for (int i = 0; i < arr.length(); i++) {
                            sPs.add(gson.fromJson(arr.get(i).toString(), ShangPin.class));
                        }
                        new AsyncTask<Void, Void, Void>() {
                            @Override
                            protected Void doInBackground(Void... params) {
                                return null;
                            }

                            @Override
                            protected void onPostExecute(Void aVoid) {
                                super.onPostExecute(aVoid);
                                adapter.swapData(sPs);
                            }
                        }.execute();
                    }
                } catch (JSONException e) {
                    Log.e("simonwLog", "错误：" + e.getMessage());
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_history:
                startActivity(new Intent(MallActivity.this, DuihuanHistoryActivity.class));
                break;
            case R.id.layout_jifen:
                startActivity(new Intent(MallActivity.this, QianDaoActivity.class));
                break;
            case R.id.tv_integral_get:
                startActivity(new Intent(MallActivity.this, IntegralGetActivity.class));
                break;
            case R.id.layout_choujiang:
                startActivity(new Intent(MallActivity.this, ChouJiangActivity.class));
                break;
        }
    }

    class SPAdapter extends RecyclerView.Adapter<SPAdapter.SPHolder> {
        private List<ShangPin> data = new ArrayList<>();

        void swapData(List<ShangPin> data0) {
            Map<Integer, ShangPin> tmpMap = new TreeMap<>(new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return o1 - o2;
                }
            });
            for (ShangPin sp : data0) {
                tmpMap.put(Integer.valueOf(sp.getSort()), sp);
            }
            this.data.clear();
            for (Object o : tmpMap.values().toArray()) {
                this.data.add((ShangPin) o);
            }
            notifyDataSetChanged();
        }

        @Override
        public SPHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new SPHolder(LayoutInflater.from(MallActivity.this).inflate(R.layout.item_sp, null));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(SPHolder holder, final int position) {
            Picasso.with(MallActivity.this).load(data.get(position).getIcon()).placeholder(R.drawable.mall_default).into(holder.iv);
            holder.tvName.setText(data.get(position).getTitile());
            holder.tvJifen.setText(data.get(position).getIntegral() + "积分");
            holder.v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final AlertDialog dialog = new AlertDialog.Builder(MallActivity.this).setTitle("兑换提醒")
                            .setMessage("本商品需消耗" + data.get(position).getIntegral() + "积分，是否兑换？")
                            .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    sp_id = data.get(position).getId();
                                    sp_integral = data.get(position).getIntegral();
                                    startActivity(new Intent(MallActivity.this, AddressesActivity.class));
                                }
                            }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).setCancelable(false).create();
                    dialog.show();
                }
            });
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class SPHolder extends RecyclerView.ViewHolder {
            private View v;
            private ImageView iv;
            private TextView tvName, tvJifen;

            SPHolder(View itemView) {
                super(itemView);
                this.v = itemView;
                iv = (ImageView) itemView.findViewById(R.id.iv);
                tvName = (TextView) itemView.findViewById(R.id.tv_name);
                tvJifen = (TextView) itemView.findViewById(R.id.tv_jifen);
            }
        }
    }

    private class SpacesItemDecoration extends RecyclerView.ItemDecoration {
        private int leftRight;
        private int topBottom;

        SpacesItemDecoration(int leftRight, int topBottom) {
            this.leftRight = leftRight;
            this.topBottom = topBottom;
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            super.onDraw(c, parent, state);
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
            //判断总的数量是否可以整除
            int totalCount = layoutManager.getItemCount();
            int surplusCount = totalCount % layoutManager.getSpanCount();
            int childPosition = parent.getChildAdapterPosition(view);
            if (layoutManager.getOrientation() == GridLayoutManager.VERTICAL) {//竖直方向的
                if (surplusCount == 0 && childPosition > totalCount - layoutManager.getSpanCount() - 1) {
                    //后面几项需要bottom
                    outRect.bottom = topBottom;
                } else if (surplusCount != 0 && childPosition > totalCount - surplusCount - 1) {
                    outRect.bottom = topBottom;
                }
                if ((childPosition + 1) % layoutManager.getSpanCount() == 0) {//被整除的需要右边
                    outRect.right = leftRight;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
            } else {
                if (surplusCount == 0 && childPosition > totalCount - layoutManager.getSpanCount() - 1) {
                    //后面几项需要右边
                    outRect.right = leftRight;
                } else if (surplusCount != 0 && childPosition > totalCount - surplusCount - 1) {
                    outRect.right = leftRight;
                }
                if ((childPosition + 1) % layoutManager.getSpanCount() == 0) {//被整除的需要下边
                    outRect.bottom = topBottom;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(EventBusTypes.AddressSelected type) {
        Address address = type.address;
        duihuanGo(address.getId());
    }

    private void duihuanGo(String id) {
        Request request = new Request.Builder().url(Server.ADD_INT_ITEM
                + "?phone_data=" + getPrefs().getString("phone", "")
                + "&id_data=" + sp_id
                + "&int_data=" + sp_integral
                + "&address_data=" + id
        ).build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(MallActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                OkHttpManager.backgroundThreadShortToast(MallActivity.this, "兑换成功");
                startActivity(new Intent(MallActivity.this, DuihuanHistoryActivity.class));
            }
        });
    }
}
